import consumerRecoderModel from "../model/consumerRecoderModel";
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import dTalkApi from '../core/dTalkApi';
import * as moment from 'moment';
import visitMonthPlanModel from '../model/visitMonthPlanModel';
import formDataService from '../services/formDataService';
import emplModel from '../model/empl2Model';
import excelExportModel from '../model/excelExportModel';
import visitFrequencyModel from '../model/visitFrequencyModel';

//新增的需求20181130
class AddNewService{
    constructor(){}
   
    //获取主管列表    1s出结果<=======针对销售无权取消拜访任务(需求四)
    async getDirectors(access_token:string){
       // console.log('开始时间!!!!',moment().format('YYYY-MM-DD HH:mm:ss'))
        if(!access_token){
            access_token=await dTalkApiUtil.getAccessToken();
        }
        let result= await dTalkApi.getRoles(access_token,100,0);
        //console.log(result,'<<<<<<<result')
        let directorArr:any[]=[];//主管列表
        if(result){
            let roles_arr:any[]=[];//
            result.list.map(item=>{
                //console.log(item,'item_item_item_')
                if(item.name=='默认'){
                    roles_arr=item.roles;
                }
            })
            //console.log(roles_arr,'<<<<<<<roles_arr')
            let director:any='';//主管角色
            if(roles_arr.length>0){
                roles_arr.map(item2=>{
                    //console.log(item2,'<<<<<<item2')
                    if(item2.name=='主管'){
                        director=item2;
                    }
                })
            }
            //console.log(director,'<===========director')
            let dataCache:any=[];
            if(director&&director.id){
                let size=130;
                let offset=0;
                let role_data=await dTalkApi.getRoleUsers(access_token,director.id,size,offset);
                //console.log(role_data,'========role_data========')
                if(role_data&&role_data.list&&!role_data.hasMore){
                    role_data.list.map(ele=>{
                        if(!directorArr.includes(ele.userid)){
                            directorArr.push(ele.userid)
                        }
                    });
                    for (const key in role_data.list) { 
                        if (role_data.list.hasOwnProperty(key)) {
                            const element = role_data.list[key];
                            dataCache.push(element)
                        }
                    }
                }
            }
            //console.log(dataCache,'<=======主管列表=============\n',directorArr.length)
            //console.log('结束时间!!!',moment().format('YYYY-MM-DD HH:mm:ss'));
        }
        return directorArr;
    }
    //获取负责人   通用方法
    async getManagers(name:string,access_token:string){
        //console.log('开始时间!!!!',moment().format('YYYY-MM-DD HH:mm:ss'))
        if(!access_token){
            access_token=await dTalkApiUtil.getAccessToken();
        }
        let result= await dTalkApi.getRoles(access_token,100,0);
        let directorArr:any[]=[];//主管列表
        let managerNames:any[]=[]//主管名字列表
        let dataCache:any=[];
        if(result){
            let roles_arr:any[]=[];//
            result.list.map(item=>{
                if(item.name==name){
                    roles_arr=item.roles;
                }
            })
            let director:any='';//负责人角色
            if(roles_arr.length){
                roles_arr.map(item2=>{
                    if(name=='销售'){
                        if(item2.name==`${name}`){
                            director=item2;
                        }
                    }else{
                        if(item2.name==`${name}负责人`){
                            director=item2;
                        }
                    }
                })
            }
            //console.log(director,'<===========director')
            if(director&&director.id){
                let size=130;
                let offset=0;
                let role_data=await dTalkApi.getRoleUsers(access_token,director.id,size,offset);
                if(role_data&&role_data.list&&!role_data.hasMore){
                    role_data.list.map(ele=>{
                        if(!directorArr.includes(ele.userid)){
                            directorArr.push(ele.userid)
                        }
                        if(!managerNames.includes(ele.name)){
                            managerNames.push(ele.name)
                        }
                    });
                    for (const key in role_data.list) { 
                        if (role_data.list.hasOwnProperty(key)) {
                            const element = role_data.list[key];
                            dataCache.push(element)
                        }
                    }
                }
            }
            //console.log(`=====${name}负责人======`,managerNames,'<<<',directorArr.length)
            //console.log('结束时间!!!',moment().format('YYYY-MM-DD HH:mm:ss'));
        }
        return {directorIds:directorArr,directorNames:managerNames,directors:dataCache};
    }

    //是否调整过拜访日期 
    //dateList:[{id:'',planDate:''}]
    //说明:调整拜访日期后,两个拜访日期不在同一个月的,拜访计划调整会失败
    //      现在的拜访日期不在原来的拜访日期之后,计划调整也会失败
    async isAdjustMonthPlanPlanDate(dateList:any){
        let num=0;
        if(dateList.length>0){
            for (let index = 0; index < dateList.length; index++) {
                let ele= dateList[index];
                let month= moment(ele.planDate).format('MM')
                let day= moment(ele.planDate).format('DD')
                if( parseInt(moment().format('MM'))==parseInt(month)&&parseInt(day)>= parseInt(moment().format('DD'))){
                    await visitMonthPlanModel.update({ _id: ele.id }, { planStatus: '待审核', isAdjust: true,planDate:ele.planDate }, { upsert: true });         
                }else{
                    num=1
                }
            }
        }
        return num;
    }

    //获取全国角色管理的模块  区域  省份 列表   
    async get_model_area_pro_list(access_token:any){
        //console.log('开始时间:',moment().format('YYYY-MM-DD HH:mm:ss'))
        let nation_id='62876001';
        let area_list:any[]=[]//区域id
        let areaName_list:any[]=[]//区域名称
        let proName_list:any[]=[]//省份名称
        let pro_list:any=[]=[]//省份id
        let model_id_list:any[]=[]//模块id
        let modelName_list:any[]=[]//模块名称
        if(nation_id){
            //模块
            let sondata_model=await dTalkApi.getSondepIdList(nation_id,false,access_token);
            model_id_list=sondata_model.department;
            modelName_list=sondata_model.deptNames;
           // console.log(modelName_list,'模块名称列表')
            //区域
            for (let index = 0; index < model_id_list.length; index++) {
                let m = model_id_list[index];
                let sondata_area=await dTalkApi.getSondepIdList(m.toString(),false,access_token)
                if(sondata_area&&sondata_area.deptNames.length>0){
                    sondata_area.deptNames.map(item=>{
                        if(!areaName_list.includes(item)){
                            areaName_list.push(item)
                        }
                    })
                }
                if(sondata_area&&sondata_area.department.length>0){
                    sondata_area.department.map(item=>{
                        if(!area_list.includes(item)){
                            area_list.push(item)
                        }
                    })
                }
            }
            //console.log(areaName_list,'区域名称列表')
            //console.log(area_list,'区域id列表')
            let sondata_all=await dTalkApi.getSondepIdList(nation_id,true,access_token)
            //省份
            sondata_all.deptNames.map(item3=>{
                if(item3){
                    if(!proName_list.includes(item3)&&!sondata_model.deptNames.includes(item3)&&!areaName_list.includes(item3)){
                        proName_list.push(item3)
                    }
                }
            })
            sondata_all.department.map(item5=>{
                if(item5){
                    if(!pro_list.includes(item5)&&!sondata_model.department.includes(item5)&&!area_list.includes(item5)){
                        pro_list.push(item5)
                    }
                }
            })
            //console.log(proName_list,'省份名称列表')
            //console.log(pro_list,'省份id列表')
            //console.log('结束时间:',moment().format('YYYY-MM-DD HH:mm:ss'))
        }
        return {nation:nation_id,modelIds:model_id_list,modelNames:modelName_list,areaIds:area_list,areaNames:areaName_list,proIds:pro_list,proNames:proName_list}
    }

    //统计一个员工一段时间的新老客户(新客户和现有客户)拜访达成率
    async getConsumerRate_one_empTime1toTime2(userid: string, date1_: string, date2_: string,typeArr:any[]){
        //实际已经拜访的客户数量
        let count_visited_consumer = await consumerRecoderModel.count({"$or":[{planType:'现有客户'},{planType:'新拓展客户'}], "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userid: userid, comment: 2});
        //计划拜访的客户数量
        let count_plan_consumer = await visitMonthPlanModel.count({ "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }],plantype:{$in:typeArr},userId: userid,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
        let consumerRate_ = 0;
        if (count_plan_consumer == 0) {
            consumerRate_ = 0;
        } else {
            consumerRate_ = count_visited_consumer / count_plan_consumer;
        }
        return consumerRate_;
    }

    //报表显示  现有客户和新拓展客户的拜访达成率  未跨月份
    async addNewReportForm(startDate2:string,endDate2:string,leaderId:string,character:string,comment:string){
        let dateData=await formDataService.getDate(startDate2,endDate2);
        let num3 =parseInt( moment(dateData.startDate).format('DD'));
        let num4 =parseInt( moment(dateData.endDate).format('DD'));
        let dateList=await formDataService.getDate2(num3,num4,dateData.startDate)//日期
        let access_token=await dTalkApiUtil.getAccessToken();
        let authority=await formDataService.getAuthrity(leaderId,access_token);
        let groupName=authority.groupName;
        let leaderDepts=authority.leaderDepts;
        let empArr=await emplModel.distinct('userId',{})
        let dataCache: any = [];//返回的数据
        let typeArr:any[]=['现有客户','新拓展客户'];
        console.log(groupName,'groupName_groupName_')
        if(groupName.includes('销售')||(!groupName.includes('销售')&&comment=='个人'&&character)){
            if(comment=='个人'){
                let userid:any=''
                if(character){
                    userid=character
                }else{
                    userid=leaderId
                }
                if(!empArr.includes(userid)){
                    return;
                }
                let empinfo=await emplModel.findOne({userId:userid,"$and":[{userId:{$ne:null}},{userId:{$ne:''}}]})
                let name:any=''
                if(empinfo){
                    name=empinfo.userName
                }else{
                    let empinfo_dd=await dTalkApi.getUserDetail(userid,access_token);
                    if(empinfo_dd&&empinfo_dd.name){
                        name=empinfo_dd.name
                    }
                }
                //在这个时间段内,哪些天员工是有计划的
                let dateArr=await visitMonthPlanModel.distinct('planDate',{"$and": [{ planDate: { "$gte": dateData.startDate } }, { planDate: { "$lte": dateData.endDate } }],plantype:{$in:typeArr},userId: userid,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] })
                if(dateList.length){
                    for (let dateindex = 0; dateindex < dateList.length; dateindex++) {
                        let date_ = dateList[dateindex];
                        let consumerRate_:any=0;
                        if(dateArr.includes(date_)){
                            consumerRate_=await addNewService.getConsumerRate_one_empTime1toTime2(userid,dateData.startDate,dateData.endDate,typeArr)
                        }
                        let consumerRate = (consumerRate_.toFixed(2)-0)*100;
                        dataCache.push({
                            comment: '一天',
                            userId: userid,
                            userName: name,
                            date:date_,
                            consumerRate: consumerRate.toFixed(0)
                        })
                    }
                }
            }
        }else{
            console.log('主管系列!!!!!')
            let emp_id_list:any[]=[]//管理的员工的id列表
            let son_deptid_list:any[]=[];//管理的部门id列表
            let son_deptname_list:any[]=[];//管理的子部门名称列表
            if(leaderDepts.length){
                for (let index2 = 0; index2 < leaderDepts.length; index2++) {
                    let deptid = leaderDepts[index2];
                    let sondata_dept=await dTalkApi.getSondepIdList(deptid,true,access_token);
                    sondata_dept.department.push(parseInt(deptid))
                    //部门id列表
                    for (let key in  sondata_dept.department) {
                        if ( sondata_dept.department.hasOwnProperty(key)) {
                            let element =  sondata_dept.department[key];
                            if(!son_deptid_list.includes(element)){
                                son_deptid_list.push(element)
                            }
                        }
                    }
                    //部门名称列表
                    for (let key3 in sondata_dept.deptNames) {
                        if (sondata_dept.deptNames.hasOwnProperty(key3)) {
                            let element3 = sondata_dept.deptNames[key3];
                            son_deptname_list.push(element3)
                        }
                    }
                    //管理的人员列表
                    let emp_data=await emplModel.distinct('userId',{"$and":[{userId:{$ne:''}},{userId:{$ne:null}},{deptId:{$in:sondata_dept.department}}]})
                    for (let key2 in emp_data) {
                        if (emp_data.hasOwnProperty(key2)) {
                            let element2 = emp_data[key2];
                            if(!emp_id_list.includes(element2)){
                                emp_id_list.push(element2)
                            }
                        }
                    }
                }
                //console.log(emp_id_list.length,'<<管理的员工id列表',son_deptid_list,'<<<管理的部门id列表',son_deptname_list,'管理的子部门名称列表')
                if(comment=='个人'){
                    if(!character){
                        console.log('领导查看全部员工!!!')
                        if(emp_id_list.length){
                            for (let index = 0; index < emp_id_list.length; index++) {
                                let ele2 = emp_id_list[index];
                                let emp=await visitMonthPlanModel.findOne({userId:ele2,"$and":[{user:{$ne:''}},{user:{$ne:null}}]})
                                if (!dataCache[emp.user]) {
                                    dataCache[emp.user] = {
                                        areaName:emp.user,
                                        consumerRate:''
                                    }
                                }
                                let consumerRate_one_emp:any = await addNewService.getConsumerRate_one_empTime1toTime2(ele2, dateData.startDate, dateData.endDate,typeArr);
                                let a=(consumerRate_one_emp.toFixed(2)-0)*100
                                dataCache[emp.user]={
                                    areaName:emp.user,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }else{
                    let son_next_deptid_list:any[]=[]//下级子部门id列表
                    let son_next_deptname_list:any[]=[]//下级子部门名称列表
                    if(groupName.includes('区域')||groupName.includes('模块')){
                        for (let index3 = 0; index3 < leaderDepts.length; index3++) {
                            let deptid2 = leaderDepts[index3];
                            let sondata2=await dTalkApi.getSondepIdList(deptid2,false,access_token)
                            //子部门id
                            for (let key in sondata2.department) {
                                if (sondata2.department.hasOwnProperty(key)) {
                                    let element = sondata2.department[key];
                                    if(!son_next_deptid_list.includes(element)){
                                        son_next_deptid_list.push(element)
                                    }
                                }
                            }
                            //子部门名称
                            for (let key in sondata2.deptNames) {
                                if (sondata2.deptNames.hasOwnProperty(key)) {
                                    let ele_name = sondata2.deptNames[key];
                                    if(!son_next_deptname_list.includes(ele_name)){
                                        son_next_deptname_list.push(ele_name)
                                    }
                                }
                            }
                        }
                    }
                    let son_proName_list:any[]=[]//模块负责人管理的省份名称列表
                    let son_pro_list:any[]=[];//模块负责人管理的省份id列表
                    if(groupName.includes('模块')&&comment=='省份'){
                        let empData=await emplModel.findOne({userId:leaderId,"$and":[{deptId:{$ne:''}},{deptId:{$ne:null}}]})
                        let leader_deptId=empData.deptId;
                        if(son_deptname_list.length){
                            son_deptname_list.map(item=>{
                                if(item){
                                    if(!son_next_deptname_list.includes(item)){//判断是否是区域部门
                                        if(!son_proName_list.includes(item)){//<----去重
                                            son_proName_list.push(item)
                                        }
                                    }
                                }
                            })
                        }
                        if(son_deptid_list.length){
                            son_deptid_list.map(item=>{
                                if(item){
                                    if(!son_next_deptid_list.includes(item)&&!leader_deptId.includes(item)){//判断是否是区域部门
                                        if(!son_pro_list.includes(item)){//<----去重
                                            son_pro_list.push(item)
                                        }
                                    }
                                }
                            })
                        }
                        console.log('模块负责人管理的省份:',son_pro_list,'省份名称:',son_proName_list)
                        console.log('模块负责人管理的区域:',son_next_deptid_list,'区域名称:',son_next_deptname_list)
                    }
                    let manage_data:any={}
                    if(groupName.includes('全国')){
                        manage_data=await this.get_model_area_pro_list(access_token);
                    }
                    if(comment=='省份'){
                        let nameList:any[]=[]
                        if(groupName.includes('区域')){//区域负责人
                            nameList=son_next_deptname_list
                        }else if(groupName.includes('模块')){ //模块负责人
                            nameList=son_proName_list
                        }else if(groupName.includes('全国')){//全国负责人
                            nameList=manage_data.proNames
                        }
                        if(nameList.length){
                            for (let proindex = 0; proindex < nameList.length; proindex++) {
                                let pro = nameList[proindex];//省份部门名称
                                if (!dataCache[pro]) {
                                    dataCache[pro] = {
                                        areaName:pro,
                                        consumerRate:''
                                    }
                                }
                                //获取pro部门下的人员列表
                                let emp_pro_list=await visitMonthPlanModel.distinct('userId',{provinceName:pro,deptId:{$in:son_deptid_list},userId:{$in:empArr}})
                                //现有客户和新拓展客户的拜访达成率
                                let rate:any=0;
                                if(emp_pro_list.length){
                                    let consumerRate_pro:any=0
                                    for (let userindex = 0; userindex < emp_pro_list.length; userindex++) {
                                        let ele_pro2 = emp_pro_list[userindex];
                                        let consumerRate_one_employee = await addNewService.getConsumerRate_one_empTime1toTime2(ele_pro2, dateData.startDate, dateData.endDate,typeArr);
                                        consumerRate_pro+=consumerRate_one_employee;
                                    }
                                    rate=consumerRate_pro/emp_pro_list.length;
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[pro]={
                                    areaName:pro,
                                    consumerRate:a.toFixed(0)
                                }
                            } 
                        } 
                    }
                    if(comment=='区域'){
                        let nameList:any[]=[]
                        if(groupName.includes('模块')){ //模块负责人
                            nameList=son_next_deptname_list
                        }else if(groupName.includes('全国')){//全国负责人
                            nameList=manage_data.areaNames
                        }
                        if(nameList.length){
                            for (let areaindex = 0; areaindex < nameList.length; areaindex++) {
                                let area_ = nameList[areaindex];//区域部门名称
                                if (!dataCache[area_]) {
                                    dataCache[area_] = {
                                        areaName:area_,
                                        consumerRate:''
                                    }
                                }
                                //获取pro部门下的人员列表
                                let emp_pro_list=await visitMonthPlanModel.distinct('userId',{areaName:area_,deptId:{$in:son_deptid_list},userId:{$in:empArr}})
                                console.log('area_area_area_area_:',area_,emp_pro_list.length)
                                //现有客户和新拓展客户的拜访达成率
                                let rate:any=0;
                                if(emp_pro_list.length){
                                    let consumerRate_pro:any=0
                                    for (let userindex = 0; userindex < emp_pro_list.length; userindex++) {
                                        let ele_pro2 = emp_pro_list[userindex];
                                        let consumerRate_one_employee = await addNewService.getConsumerRate_one_empTime1toTime2(ele_pro2, dateData.startDate, dateData.endDate,typeArr);
                                        consumerRate_pro+=consumerRate_one_employee;
                                    }
                                    rate=consumerRate_pro/emp_pro_list.length;
                                }
                                let a=(rate.toFixed(2)-0)*100
                                dataCache[area_]={
                                    areaName:area_,
                                    consumerRate:a.toFixed(0)
                                }
                            }
                        }
                    }
                }
            }
        }
        let list:any[]=[]
        for (const key in dataCache) { //移植dataCache当中的属性到list当中
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        if(list.length==0){
            list.push({
                areaName:'',
                consumerRate:0
            })
        }
        console.log(list,'list_list_list_list_list_list_list_list_新老客户拜访达成率')
        return list;
    }

    //导出excel表格   //   0464063017881719:汪卡     0651490869921242:熊令 全国  01625422314596:武晓丽
    async exportNewReportForm(startDate:string,endDate:string,leaderId:string,character:string){
        console.log('开始时间:',moment().format('HH:mm:ss'))
        let conf2:any[]=[];//返回的数据
        let col: any[] = ['员工id','员工姓名','区域','TSM(主管)','日期','现有客户计划拜访数','现有客户实际完成拜访数','现有客户拜访达成率','新客户计划拜访数','新客户实际完成拜访数','新客户拜访达成率','出差天数'];
        conf2.push(col);
        //时间不跨月份
        let dateData=await formDataService.getDate(startDate,endDate)
        let startDate2 = dateData.startDate;
        let endDate2= dateData.endDate;
        //权限
        let access_token=await dTalkApiUtil.getAccessToken();
        console.log('access_token:',access_token)
        let sondata_nation=await addNewService.get_model_area_pro_list(access_token);
        let authority=await formDataService.getAuthrity(leaderId,access_token)
        let groupName=authority.groupName;
        let leaderDepts = authority.leaderDepts
        //console.log(groupName,'groupName_groupName_groupName_')
        let arr=await emplModel.distinct('userId',{})
        if(groupName.includes('销售')||(!groupName.includes('销售')&&character)){
            let userId: any = ''
            if (!character) {
                userId = leaderId
            } else {
                userId = character;
            }
            if(!(arr.includes(userId))){
                return;
            }
            let dateList=await visitMonthPlanModel.distinct('planDate',{userId:userId,"$and": [{ planDate: { "$gte": startDate2 } }, { planDate: { "$lte": endDate2 } }]})
            dateList.sort();//排序
            let data5=await addNewService.getexcelinfoByUserId(userId,access_token,sondata_nation)
            if(dateList.length>0){
                for (let dateindex = 0; dateindex < dateList.length; dateindex++) {
                    let date_2 = dateList[dateindex];
                    let m_data: any = [];//一行数据
                    m_data.push(userId) //员工id
                    m_data.push(data5.name)//员工姓名
                    m_data.push(data5.area_) //所在区域或者模块的名称
                    m_data.push(data5.manager)//主管
                    m_data.push(date_2)//日期
                    let data4=await excelExportModel.findOne({userId:userId,date_:date_2})
                    if(data4){
                        m_data.push(data4.visitCount_plan_nowConsumer)//现有客户计划拜访数量
                        m_data.push(data4.nowConsumerCount_visit)//现有客户完成的拜访数量
                        m_data.push(data4.nowConsumerRate)//现有客户拜访达成率
                        m_data.push(data4.newConsumerCount_plan) //计划拜访的新客户数量
                        m_data.push(data4.newConsumerCount_visit)  //实际已经拜访的新客户数量
                        m_data.push(data4.newConsumerRate)//新客户拜访达成率
                        m_data.push(data4.unBase_check)//出差天数
                    }else{
                        m_data.push(0)
                        m_data.push(0)
                        m_data.push('0.00')
                        m_data.push(0) 
                        m_data.push(0) 
                        m_data.push('0.00')
                        m_data.push(0)
                    }
                    conf2.push(m_data)
                }
            }
        }else{
            console.log('部门主管系列!!!!')
            if(!character){
                //这个时间段内的哪些天有员工的拜访计划
                let dateList=await visitMonthPlanModel.distinct('planDate',{"$and": [{ planDate: { "$gte": startDate2 } }, { planDate: { "$lte": endDate2 } }]})
                dateList.sort();//排序
                let userid_list=await visitMonthPlanModel.distinct('userId',{planDate:{$in:dateList}});
                console.log(dateList.length,'日期列表-dateList',userid_list.length,'有计划的员工id列表')
                //获取领导管理的所有员工
                let userList:any[]=[];//leader管理的所有员工
                if(leaderDepts.length>0){
                    for (let index = 0; index < leaderDepts.length; index++) {
                        let dept_id = leaderDepts[index];
                        let sondata2=await dTalkApi.getSondepIdList(dept_id,true,access_token);
                        sondata2.department.push(parseInt(dept_id));
                        let empList=await emplModel.distinct("userId",{"$and":[{userId:{$ne:''}},{userId:{$ne:null}},{userId:{$in:userid_list}},{userDept:{$in:sondata2.department}}]})
                        for (let key2 in empList) {
                            if (empList.hasOwnProperty(key2)) {
                                let element2 = empList[key2];
                                if(!userList.includes(element2)){
                                    userList.push(element2)
                                }
                            }
                        }
                    }
                    console.log(userList.length,'管理的员工列表',moment().format('HH:mm:ss'))
                    let repeatArr:any[]=[];
                    let basedataArr:any[]=[]
                    if(userList.length>0){
                        for (let userindex = 0; userindex < userList.length; userindex++) {
                            let userid_= userList[userindex];
                            if(!repeatArr.includes(userid_)){
                                let data5=await addNewService.getexcelinfoByUserId(userid_,access_token,sondata_nation)
                                basedataArr.push({
                                    id:userid_,
                                    name:data5.name,
                                    area_deptid:data5.area_deptid,
                                    area_:data5.area_,
                                    manager:data5.manager
                                })
                                repeatArr.push(userid_)
                            }
                        }
                    }
                    //console.log(basedataArr,'basedataArr_')
                    if(dateList.length>0){
                        for (let dateindex = 0; dateindex < dateList.length; dateindex++) {
                            let date2 = dateList[dateindex];
                            let empList=await visitMonthPlanModel.distinct('userId',{planDate:date2,userId:{$in:userList}})
                            if(basedataArr.length>0){
                                for (let baseindex = 0; baseindex < basedataArr.length; baseindex++) {
                                    let base = basedataArr[baseindex];
                                    // if(dateindex==0){
                                    //     console.log(date2,'????',base.name,'??????',dateindex,'<<<dateindex,baseindex>>>',baseindex,'userList.length>>>>',userList.length)
                                    // }
                                    console.log(date2,'????',base.name,'??????',dateindex,'<<<dateindex,baseindex>>>',baseindex,'userList.length>>>>',userList.length)
                                    if(empList.includes(base.id)){
                                        let m_data: any = [];//一行数据
                                        m_data.push(base.id) //员工id
                                        m_data.push(base.name)//员工姓名
                                        m_data.push(base.area_) //所在区域或者模块的名称
                                        m_data.push(base.manager)//主管
                                        m_data.push(date2)//日期
                                        let data4=await excelExportModel.findOne({userId:base.id,date_:date2})
                                        if(data4){
                                            m_data.push(data4.visitCount_plan_nowConsumer)//现有客户计划拜访数量
                                            m_data.push(data4.nowConsumerCount_visit)//现有客户完成的拜访数量
                                            m_data.push(data4.nowConsumerRate)//现有客户拜访达成率
                                            m_data.push(data4.newConsumerCount_plan) //计划拜访的新客户数量
                                            m_data.push(data4.newConsumerCount_visit)  //实际已经拜访的新客户数量
                                            m_data.push(data4.newConsumerRate)//新客户拜访达成率
                                            m_data.push(data4.unBase_check)//出差天数
                                        }else{
                                            m_data.push(0)
                                            m_data.push(0)
                                            m_data.push('0.00')
                                            m_data.push(0) 
                                            m_data.push(0) 
                                            m_data.push('0.00')
                                            m_data.push(0)
                                        }
                                        conf2.push(m_data)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        console.log('结束时间:',moment().format('HH:mm:ss')) 
        return conf2;
    }



    async getexcelinfoByUserId(userid_:any,access_token:any,sondata_nation:any){
        let user_name:any=''; //员工姓名
        let user_deptId:any='';//员工所在部门是省份时,字段段的值是员工所在区域的id,员工所在部门是模块 区域 全国时,其值是部门id
        let name3:any=''; //所在的区域或者模块
        let manager_list:any=[]//部门主管
        //员工姓名
        let empl_data=await emplModel.findOne({userId:userid_,'$and':[{userName:{$ne:null}},{userName:{$ne:''}}]})
        if(empl_data){
            user_name=empl_data.userName
            user_deptId=empl_data.userDept[0]
        }else{
            let employeeInfo = await dTalkApi.getUserDetail(userid_,access_token);
            if (employeeInfo&&employeeInfo.name) {
                user_name=employeeInfo.name;
            }  
            if (employeeInfo&&employeeInfo.department) {
                user_deptId=employeeInfo.department;
            }      
        }
        //所在的区域或者模块
        if(sondata_nation&&user_deptId){
            if(sondata_nation.modelIds.includes(user_deptId)){
                console.log('销售所在部门属于模块',userid_)
                let data3=await visitMonthPlanModel.findOne({manageModel:user_deptId,'$and':[{manageModelName:{$ne:null}},{manageModelName:{$ne:''}}]})
                if(data3){
                    name3=data3.manageModelName
                }
            }else if(sondata_nation.areaIds.includes(user_deptId)){
                console.log('销售所在部门属于区域',userid_)
                let data3=await visitMonthPlanModel.findOne({area:user_deptId,'$and':[{areaName:{$ne:null}},{areaName:{$ne:''}}]})
                if(data3){
                    name3=data3.areaName
                }
            }else if(sondata_nation.proIds.includes(user_deptId)){
                console.log('销售所在部门属于省份',userid_)
                let data3=await visitMonthPlanModel.findOne({province:user_deptId,'$and':[{areaName:{$ne:null}},{areaName:{$ne:''}}]})
                if(data3){
                    name3=data3.areaName
                }
                let parentData=await dTalkApi.list_parent_depts(userid_,access_token)
                //console.log(parentData,'<<<<<<<<<<<<',user_name,user_deptId)
                if(parentData&&parentData.department&&parentData.department.length){
                   
                    let num5=0;
                    parentData.department.map(item=>{
                        let num3=item.indexOf(user_deptId);
                        if(num3!=-1){
                            user_deptId='';
                            num3+=1;
                            if(!user_deptId){
                                user_deptId=item[num3]
                            }
                        }
                    })
                }
            }else if(sondata_nation.nation==user_deptId){
                console.log('销售所在部门属于全国')
                name3='全国'
            }
        }
        let deptinfo3=await dTalkApi.getDeptDetail(user_deptId,access_token);
        if(!name3){
            if(deptinfo3&&deptinfo3.name){
                name3=deptinfo3.name
            } 
        }
        //部门主管
        if(deptinfo3&&deptinfo3.deptManagerUseridList){
            let dept_managers=deptinfo3.deptManagerUseridList
            if(dept_managers.includes('|')){
                dept_managers = dept_managers.substr(0, dept_managers.length - 1)
                let manager_list_=dept_managers.split('|')
                for (let index = 0; index < manager_list_.length; index++) {
                    let item = manager_list_[index];
                    //console.log(item,'区域部门主管的userid',index)
                    let empl_=await emplModel.findOne({userId:item,'$and':[{userName:{$ne:null}},{userName:{$ne:''}}]})
                    if(empl_&&empl_.userName&&!manager_list.includes(empl_.userName)){
                        manager_list.push(empl_.userName)
                    }
                }
            }else{
                let empl_=await emplModel.findOne({userId:dept_managers,'$and':[{userName:{$ne:null}},{userName:{$ne:''}}]})
                if(empl_&&empl_.userName&&!manager_list.includes(empl_.userName)){
                    manager_list.push(empl_.userName)
                }
            }
        }
        //console.log(user_name,'<<<user_name,area_>>>>',name3,user_deptId,'<<<<<user_deptId,manager>>>>',manager_list)
        let manager_=manager_list.join('|');
        return {id:userid_,name:user_name,area_deptid:user_deptId,area_:name3, manager:manager_}
    }



    //================================================下面是新增的方法==2019-01-15===================================================


    /* //本地补充完善员工的组织架构信息<=================暂时没有使用(无用)
    async upEmplOrganizeInfo(){
        console.log('本地补充完善员工的组织架构信息开始!!!',moment().format('YYYY-MM-DD HH:mm:ss'))
        let empArr=await addNewService.getManagers('销售','');
    
        console.log(empArr.directorIds.length,'empArr_销售的useid列表')
        let infolist=await visitMonthPlanModel.distinct('userId',{userId:{$in:empArr.directorIds},comment:1,month:'12',"$and":[{nationName:{$ne:''}},{nationName:{$ne:null}},{nation:{$ne:''}},{nation:{$ne:null}}]})
        console.log(infolist.length,'已经完善组织架构信息')
        let planlist=await visitMonthPlanModel.distinct('userId',{month:'12',userId:{$in:empArr.directorIds}});
        console.log('有计划的员工id列表:',planlist.length)
        let unlist:any[]=[]//未完善组织架构信息的员工id列表
        if(planlist.length>0){
            planlist.map(id=>{
                if(!infolist.includes(id)){
                    unlist.push(id)
                }
            })
        }
        console.log(unlist.length,'unlist_unlist_unlist_unlist_')
        if(unlist.length>0){
            let cache:any={}
            let access_token=await dTalkApiUtil.getAccessToken();
            for (let unindex = 0; unindex < unlist.length; unindex++) {
                let id = unlist[unindex];
                let emp_=await emplModel.findOne({userId:id})
                let s=await visitMonthPlanService.getUserOriginizationById(id,cache,access_token);
                //console.log(s,'s_s_s_s_s_s_',emp_.userName)
                let provinceName= s[0];
                let areaName = s[1];
                let manageModelName = s[2];
                let teamName= s[3];
                let nationName = s[4];
                let province =  s[5];
                let area=  s[6];
                let model =  s[7];
                let team =  s[8];
                let nation =  s[9];
                let roles=s[10];
                console.log("完善组织架构信息!")
                let a2 = await visitMonthPlanModel.create({
                    sourceId: '',
                    userId: id,
                    user: emp_.userName,
                    avatar: emp_.avatar,
                    jobnumber: emp_.jobnumber,
                    deptId: emp_.userDept,
                    provinceManager: '',
                    areaManager: '',
                    modelManager: "",      //模块负责人
                    nationalManager: "",//全国负责人
                    city: emp_.userArea,
                    roles: roles,     //角色
                    province: province,//员工所在省份
                    area: area,//员工所在区域
                    manageModel: model,     //员工所在模块
                    team: team,//员工所在团队
                    nation: nation,
                    provinceName: provinceName,//省份名称
                    areaName: areaName,//区域名称
                    manageModelName: manageModelName,//模块名称
                    teamName: teamName,//团队名称
                    nationName: nationName,//全国名称
                    month: moment().format('MM'),
                    visitRecoder: '',
                    channel: '',
                    mark: '',
                    planDate: '',
                    consumerName: '',
                    consumerCode: '',
                    //=======新增============
                    consumerAddress:'',//客户地址
                    isAdjust:false,
                    //=======新增============
                    rest: '',
                    meeting: '',
                    plantype: '',
                    planStatus: '',
                    customerType:'',
                    purpose: '',
                    comment: 1,
                    cancelApply: '否',
                    remark: '',
                    leadIndate: ''
                });
                console.log(a2._id,'a2_a2_a2_a2_a2_a2_a2_a2_',emp_.userName,unindex)
            }
        }
        console.log('本地补充完善员工的组织架构信息结束!!!',moment().format('YYYY-MM-DD HH:mm:ss'))
    } */
    


    //拜访频次设定
    async getSetVisitFrequency(codeList:any[]){
        let num=0;
        let year=moment().format('YYYY')
        let month=moment().format('MM')
        if(codeList.length>0){
            for (let index = 0; index < codeList.length; index++) {
                let element = codeList[index];
                //element={userId:'',number:0,code:''}
                let b=await visitFrequencyModel.update({userId:element.userId,consumerCode:element.code},{visitSetCount:element.number,year:year,month:month,setTime:moment().format('YYYY-MM-DD HH:mm:ss')});
                console.log(b,'b_b_b_b_b_',index,'=====',element)
                if(b.ok>0){
                    num=1;
                }
            }
        }
        return num;
    }

    //拜访频次显示
    async showVsitFrequency(leaderId:string,access_token:string){
        let year=moment().format('YYYY')
        let month=moment().format('MM')
        //获取领导管理的人员列表
        let authority=await formDataService.getAuthrity(leaderId,access_token);
        let sonData=await formDataService.getsonDept(authority.leaderDepts,true,access_token,[]);
        let manaArr=sonData.userIdData;
        let data=await visitFrequencyModel.find({year:year,month:month,"$and":[{userid:{$in:manaArr}},{userid:{$ne:leaderId}}]}).sort({userId:1});
        let dataCache:any=[]
        if(data.length>0){
            for (let index = 0; index < data.length; index++) {
                let element = data[index];
                if(!dataCache[element.userId]){
                    dataCache[element.userId]={
                       planDate:element.userId,
                       data:[]
                    }
                }
                dataCache[element.userId].data.push({
                    id: element._id,//隐藏  mongodb数据库自建的_id
                    consumerCode:element.consumerCode,//客户编码
                    visitSetCount:element.visitSetCount,//设定的拜访频次
                    userId:element.userId,//员工id
                    unit:element.unit, //单位 1:周  2:月
                    visitedCount:element.visitSetCount,//员工已经拜访的次数
                    setTime:element.setTime
                });
            }
        }
        let list:any[]=[]
        for (const key in dataCache) {
            if (dataCache.hasOwnProperty(key)) {
                let element = dataCache[key];
                list.push(element)
            }
        }
        return list
    }
    //判断员工本月是否可以新建拜访计划
    async isBuildPlan(userId:string,month:string,year:string){
        let data=await visitFrequencyModel.find({userId:userId,month:month,year:year})
        let visitArr:any[]=[]   //本月可以拜访的客户列表
        if(data.length>0){
            data.map(it=>{
                if(it.visitSetCount>it.visitedCount){
                    if(!visitArr.includes(it.consumerCode)){
                        visitArr.push(it.consumerCode)
                    }
                }
            })
        }
        let json:any[]=[]
        let data2=await consumerRecoderModel.find({userid:userId,comment:1,consumerCode:{$in:visitArr}});
        if(data2.length>0){
            for (let index2 = 0; index2 < data2.length; index2++) {
                let element = data2[index2];
                json.push({
                    id:element._id,//id
                    city:element.city,
                    cityType:element.cityType,
                    month:element.month,//月份
                    comment:element.comment,//说明
                    code:element.consumerCode,//客户编码
                    name:element.consumerName,//客户名称
                    consumerAddress:element.consumerAddress,//客户地址
                    type1:element.typeOne,//客户类型1
                    type2:element.typeTwo,//客户类型2
                    type3:element.typeThree,//客户类型3
                    type4:element.typeFour, //客户类型4
                    eployeeName:element.userName,//员工名字
                    jobnumber:element.jobnumber   //员工工号    
                })
            }
        }
        return json;
    }



}
let addNewService=new AddNewService();
export default addNewService;